/**
 * @fileOverview 容器
 * @author goodzsq@gmail.com
 */

module.exports = {
    attributes: {
        children: {
            label: '子组件',
            type: 'datatype.Array',
            order: Infinity,
            defaultValue: [],
            setter: function(v) {
                if (typeof this.children !== 'array') {
                    this.children = [];
                } else {
                    this.children.length = 0;
                }
                for (var i = 0; i < v.length; i++) {
                    this.addChild(v[i]);
                }
            },
            getter: function() {
                return this.children;
            }
        }
    },
    methods: {
        addChild: function(attr, at) {
            var child = gg.object(attr, this);
            this.applyAttr('children', 'add', child, at);
            if (at == null) {
                at = this.children.length - 1;
            }
            this.trigger('onAddChild', child, at);
            this.listenTo(child, 'destroy', function(obj) {
                this.removeChild(obj);
            });
        },
        removeChildAt: function(at) {
            var child = this.children[at];
            console.log('removechild', child.cid);
            child.parent = null;
            this.children.splice(at, 1);
            this.trigger('onRemoveChild', child, at);
        },
        removeChild: function(obj) {
            var at = _.indexOf(this.children, obj);
            this.removeChildAt(at);
        }
    },
    events: {
        onAddChild: 'addchild',
        onRemoveChild: 'removechild'
    }
};